package com.sihan.framework.etm.controller;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.framework.exception.BusinessException;
import com.sihan.framework.etm.entity.BooleanResultModel;
import com.sihan.framework.etm.entity.UploadModel;

import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;

@Api(tags = "上传资源管理")
@RestController
@RequestMapping("/common/v0/file")
@Slf4j
public class FileRestController {
	  @Value("${projectPicHost:}")
	  private String picHost;
	  
	/**
	 * 上传文件
	 * @param file
	 * @param type
	 * @return
	 * @throws Exception
	 * @return ResponseEntity<?>
	 * @author 张荣英
	 * @date Mar 20, 2020 11:04:55 PM
	 */
	@PostMapping("/upload")
	public ResponseEntity<?> upload(MultipartFile file) throws Exception {
		UploadModel uploadModel = new UploadModel();
		String contentType = file.getContentType();
		MultiValueMap<String, String> headers = new HttpHeaders();
		List<String> list = new ArrayList<>();
		list.add("text/html");
		headers.put("Content-Type", list);
//		File saveFile = null;
		boolean isImg = contentType.startsWith("image");
		//gsl 20200324 更改为按后缀名生成目录 start
//		if (contentType.startsWith("image")) {
//			isImg = true;
//			saveFile = new File(picHost);
//		} else {
//			saveFile = new File(fileHost);
//		}
		uploadModel.setIsImg(isImg);
//		String fileName = file.getOriginalFilename();
//		String suffix = fileName.substring(fileName.lastIndexOf(".")+1, fileName.length());
//		String path = fileHost+File.separator+suffix+File.separator;
//		saveFile = new File(path);
//		//gsl 20200324 更改为按后缀名生成目录 end
//		if (!saveFile.exists()) {
//			saveFile.mkdirs();
//		}
		String filename = file.getOriginalFilename();
		String finalFileName = getFileName(filename);
		try(FileOutputStream out = new FileOutputStream(new File(picHost, finalFileName))){
			byte[] bytes = file.getBytes();
			out.write(bytes);
			String url = picHost + finalFileName;
			uploadModel.setSuccess(true);
			uploadModel.setUrl(url);
			uploadModel.setFilename(finalFileName);
			uploadModel.setFakeFilename(filename);
			out.close();
		}catch(Exception e) {
			log.error("上传文件异常",e);
		}
		
		//gsl 20200324 更改为按后缀名生成目录 start
//		if (isImg) {
//			uploadModel.setUrl(picHost);
//		} else {
//			uploadModel.setUrl(fileHost);
//		}
		//uploadModel.setUrl(path);
		//gsl 20200324 更改为按后缀名生成目录 end
		
		// String imageName = pdfToJPG(finalFileName);
		if(isImg) {
			uploadModel.setImageName(finalFileName);
		}
		return new ResponseEntity<UploadModel>(uploadModel, headers, HttpStatus.OK);
	}

	private String getFileName(String filename) {
		String finalFileName = "";
		String[] splits = filename.split("\\.");
		if (splits.length > 1) {
			String ext = splits[splits.length - 1];
			for (int i = 0; i < splits.length - 1; i++) {
				finalFileName += splits[i] + ".";
			}
			finalFileName = finalFileName.substring(0, finalFileName.length() - 1);
			finalFileName = finalFileName + "-" + System.currentTimeMillis() + "." + ext;
		} else {
			finalFileName = filename + "-" + System.currentTimeMillis();
		}
		finalFileName = finalFileName.replaceAll("[\\s&'+#%]", "-");
		return finalFileName;
	}

	/**
	 * 删除文件
	 * @param requestModel
	 * @return
	 * @throws IOException
	 * @return BooleanResultModel
	 * @author 张荣英
	 * @date Mar 20, 2020 11:05:40 PM
	 */
	@RequestMapping(value = "/delete.json", method = RequestMethod.POST)
	public @ResponseBody BooleanResultModel fileDelete(@RequestBody UploadModel requestModel) throws IOException {
		BooleanResultModel result = new BooleanResultModel();
		// String fileName = requestModel.getFilename();
		// File file = new File(webConfig.getFarmLogFileUploadHost(),fileName);
		// if (file.exists()) {
		// boolean delete = file.delete();
		// if (delete) {
		// File imageFile = new File(webConfig.getPdfPicUploadHost()
		// +fileName.substring(0, fileName.lastIndexOf("-"))+"/");
		// if (imageFile.exists()) {
		// deleteDir(imageFile);
		// }
		// } else {
		// result.setResult(false);
		// return result;
		// }
		// } else {
		// result.setResult(false);
		// return result;
		// }
		result.setResult(true);
		return result;
	}

	/**
	 * 递归删除目录下的所有文件及子目录下所有文件
	 * 
	 * @param dir
	 *            将要删除的文件目录
	 * @return boolean Returns "true" if all deletions were successful. If a
	 *         deletion fails, the method stops attempting to delete and returns
	 *         "false".
	 */
	public boolean deleteDir(File dir) {
		if (dir.isDirectory()) {
			String[] children = dir.list();
			for (int i = 0; i < children.length; i++) {
				boolean success = deleteDir(new File(dir, children[i]));
				if (!success) {
					return false;
				}
			}
		}
		// 目录此时为空，可以删除
		return dir.delete();
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static void clean(final Object buffer) throws Exception {
		AccessController.doPrivileged(new PrivilegedAction() {
			@SuppressWarnings("restriction")
			public Object run() {
				try {
					Method getCleanerMethod = buffer.getClass().getMethod("cleaner");
					getCleanerMethod.setAccessible(true);
					sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod.invoke(buffer, new Object[0]);
					cleaner.clean();
				} catch (Exception e) {
					log.error("异常",e);
				}
				return null;
			}
		});
	}
	
	@PostMapping("/load/template")
	public void loadTemplateFile(HttpServletRequest request, HttpServletResponse response,String fileName) {
		BufferedOutputStream bos = null;
		InputStream inputStream = null;
		ClassPathResource cpr = new ClassPathResource("excel/"+fileName);
		
        
		byte[] buffer = new byte[1024];
        try {
        	String ifileName = new String((fileName).getBytes(),
    				"iso8859-1");
    		response.setContentType("application/vnd.ms-excel;charset=UTF-8");
    		response.setHeader("Content-Disposition", "attachment;filename=" + ifileName);
    		response.setCharacterEncoding("utf-8");
        	inputStream = cpr.getInputStream();
			bos = new BufferedOutputStream(response.getOutputStream());
			int bytesRead = 0;
	        while ((bytesRead = inputStream.read(buffer)) != -1) {
	            bos.write(buffer, 0, bytesRead);
	        }
		} catch (IOException e) {
			throw new BusinessException("下载模板文件异常",e);
		}finally{
        	try {
        		if(null != inputStream) {
        			inputStream.close();
        		}
			} catch (IOException e) {
				log.error("下载模板文件关闭流异常",e);
			}
        	try {
        		if(bos != null)
        			bos.close();
			} catch (IOException e) {
				log.error("下载模板文件关闭流异常",e);
			}
        }
        
	}
}
